package com.example.Interceptor;

import com.example.Utils.CurrentHolder;

import com.example.Utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("拦截器放行前操作");
        //1.获得url路径
        String uri=request.getRequestURI();
        if(uri.contains("login")){
            return true;
        }
        //2.非登录请求，获取并判断token是否为空
        String token=request.getHeader("token");
        if(token==null|| token.isEmpty()){
            log.info("token为空,响应401");
            response.setStatus(401);
            return false;
        }
        try {
            Claims claims = JwtUtils.parseToken(token);
            Integer id = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentEmpId(id);
        } catch (Exception e) {
            //校验失败，令牌不合法
            log.info("令牌不合法，响应401");
            response.setStatus(401);
            return false;
        }
        log.info("令牌合法，放行");
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentHolder.removeCurrentEmpId();
    }
}
